﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace ClassLibrary1.entity
{
    //[XmlRoot("car")]
    [Serializable]
    public class Car : BaseEntity
    {
       // [XmlElement("book")]
        public Booking booking { get; set; }

        //[XmlElement("driver")]
        public Driver driver { get; set; }

      //  [XmlElement("model")]
        public string model { get; set; }

        public Car()
        {
            int id = 1;
            while (Car.FindById(id.ToString()) != null)
            {
                id++;
            }
            this.id = id;
            
        }

        public Car(string[] mas)
        {
            this.id = new Car(mas[0]).id;
            Upd(mas.Skip(1).ToArray());
        }

        public Car(string id) 
        {
            if (Car.FindById(id) != null) return; 
                int.TryParse(id, out this.id);   
        }

        public static Car FindById(string id) 
        {
            return (Car)Data.entity.FirstOrDefault(item => item.GetType() == typeof(Car) && item.id == int.Parse(id));
        }

        public static List<BaseEntity> FindAll() 
        {
           return Data.entity.FindAll(item => item.GetType() == typeof(Car));
        }

        public override void Upd(string[]mas)
        {
            try
            {
                this.model = mas[0];
            }
            catch (Exception) { }
            try { 
                this.driver = Driver.FindById(mas[1]);
                if (this.driver != null) this.driver.car = this;
            }
            catch (Exception) { }
            try { 
                this.booking = Booking.FindById(mas[2]);
                if (this.booking != null) this.booking.car = this;
            }
            catch (Exception) { }
        }

        public override string Write()
        {
            string s = "car"+ " " + this.id;
            s += " ";
            if (this.model != null && this.model.Trim() != "") s += this.model.ToString();
            s += " ";
            if (this.driver != null) s += this.driver.id.ToString();
            s += " ";
            if (this.booking != null) s += this.booking.id.ToString();    
            return s;
        }

        public bool Equals(Booking a)
        {
            if (this.id.Equals(a.id)) return true;
            return false;
        }
    }
}
